package com.abbas.CayTcore.base

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import java.lang.ref.WeakReference

abstract class BasePresenter<V : BaseView,M : BaseModel>: LifecycleObserver {

    constructor(){
        Log.e("Tag","create a presenter")
    }

    protected lateinit var view: WeakReference<V>
    protected lateinit var model: M
    protected lateinit var fragmentViewLifecycleOwner: LifecycleOwner
    protected val handler: Handler = Handler(Looper.getMainLooper())

    abstract fun initModel(): M;

    fun attach(view: V){
        this.view = WeakReference(view)
        model = initModel()
        Log.e("Tag","attach presenter")
    }

    fun attach(fragment: Fragment){
        this.view = WeakReference(fragment as V)
        fragmentViewLifecycleOwner = fragment.viewLifecycleOwner
        model = initModel()
        initData()
        Log.e("Tag","attach presenter")

    }

    open fun initData(){

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun deAttach(){
        view.let {
            view.clear()
        }
        Log.e("Tag","deAttach presenter")
    }

}